#!/usr/bin/perl

# Created by Igor Markov, Summer 2001

# This script converts a cnf instance in DIMACS format
# into a hypergraph that can be placed by the Capo placer.

open(NODES,">out.nodes");
open(NETS ,">out.nets1" );
open(AUX  ,">out.aux " );
chomp($today=`date`);
chomp($Iam  =`whoami`);
chomp($host =`uname -a`);

$line="";

while (<>)
{
   next if /^\s*c/i;
   next if /^\s*$/i;
   if (/^\s*p\s+cnf\s+(\d+)\s+(\d+)/i)
   {
      $vars=$1;
      $clauses=$2;
      $numPins=0;
      print " $vars variables and $clauses clauses\n";
      init();
      next;
   }
   die "Do not know num. variables!\n" unless $vars;
   unless (/ 0$/ || / 0 /) { $line="$line $_"; next; }
   $curr="$line $_"; $line="";
   $curr=~ s/^\s+//g;
   @net=split(/\s+/,$curr);
   next unless $#net>1;
   die "Missing ending 0 in clause $_\n" if pop(@net)!=0;
#  print " @net ", "\n";
   print NETS "NetDegree : ",1+$#net," \n";
   foreach $v (@net) 
   { 
     if ($v =~ s/-//g) { print NETS "v$v O\n"; }
     else              { print NETS "v$v I\n"; }
     $numPins++; 
   }
}
close(NETS);
open(NETS ,"<out.nets1" );
open(RealNETS,">out.nets");
while(<NETS>)
{
    s/NumPins : .*$/NumPins : $numPins/;
    print RealNETS;
}
close(NETS);
close(RealNETS);
unlink "out.nets1";

print << "END";
  The conversion finished successfully.
  Output files are: out.aux, out.nodes and out.nets
END

sub init()
{
      print NODES << "END";
UCLA nodes   1.0
# Generated by cnf2nets (user $Iam)
# Host : $host
# Translation date: $today
NumNodes : $vars
NumTerminals : 0
END
      for($n=1;$n<=$vars;$n++) 
      { $tmp="v$n"; printf(NODES " %20s 1 1\n",$tmp); }

      print NETS << "END";
UCLA nets   1.0
# Generated by cnf2nets (user $Iam)
# Host : $host
# Translation date: $today
# NumNets : $clauses
  NumPins : [missing]
END
      print AUX  << "END";
HGraph : out.nodes out.nets
END
}
